package com.ddpt.gateway.filter;

import com.ddpt.gateway.filter.base.BaseLimitFilter;
import com.ddpt.gateway.filter.config.LimitConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * ip黑白名单限制
 */
@Slf4j
@Component
public class IpFilter extends BaseLimitFilter implements GlobalFilter, Ordered {

    @Autowired
    private LimitConfiguration configuration;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        PathMatcher matcher = new AntPathMatcher();
        String path = exchange.getRequest().getURI().getPath();
        if(!CollectionUtils.isEmpty(configuration.getNotIpUrl())){
            //判断当前url是否跳过ip限制
            if(configuration.getNotIpUrl().stream().anyMatch(url -> matcher.match(url,path))){
                return chain.filter(exchange);
            }
        }
        if(CollectionUtils.isEmpty(configuration.getIpUrl())){
            return chain.filter(exchange);
        }
        if(configuration.getIpUrl().stream().noneMatch(url -> matcher.match(url, path))){
            return chain.filter(exchange);
        }
        String clientIP = getIp(exchange.getRequest());
        Set<String> whiteIps = configuration.getWhiteIps();
        if(CollectionUtils.isEmpty(whiteIps)){
            whiteIps = new HashSet<>(Collections.singletonList("**"));
        }
        Set<String> blackIps = configuration.getBlackIps();
        if(CollectionUtils.isEmpty(blackIps)){
            blackIps = new HashSet<>(Collections.singletonList("/error"));
        }
        boolean match = blackIps.stream().anyMatch(ip -> matcher.match(ip, clientIP));
        if(!match){
            match = whiteIps.stream().noneMatch(ip -> matcher.match(ip, clientIP));
        }
        if(match){
            log.warn("---ip[{}]被限制访问,携带token:{}---",clientIP,exchange.getRequest().getHeaders().getFirst("token"));
            return writeResponse(exchange,HttpStatus.valueOf(configuration.getIpLimitHttpStatus()),configuration.getIpLimitMsg());
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
